import datetime
import re
from flask import request,current_app,make_response, jsonify
from flask import session

from info import redis_store,constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue
import json
import random


# 退出登陆
@passport_blue.route('/logout',methods=["POST"])
def logout():
    # 清除sessionx信息
    session.pop("user_id",None)
    # 返回响应
    return jsonify(errno=RET.OK,errmsg="退出成功")


# 登陆成功
@passport_blue.route('/login',methods=["POST"])
def login():
    # 获取参数
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    # 校验参数,为空校验
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 通过用户手机号,到数据库查询用户对象
    try:
        user = User.query.filter(User.mobile == mobile).first()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")
    # 判断用户是否存在
    if not user:
        return jsonify(errno=RET.NODATA,errmsg="该用户不存在")
    # 校验密码是否正确
    if not user.check_password(password):
        return jsonify(errno=RET.DATAERR,errmsg="密码错误")
    # 将用户的登陆信息保存在session
    session["user_id"] = user.id

    # 记录用户的最后登陆时间
    user.last_login = datetime.datetime.now()



    # 返回响应
    return jsonify(errno=RET.OK,errmsg="登陆成功")


#注册成功
@passport_blue.route("/register",methods=["POST"])
def register():
    # json_data = request.data
    # dict_data =json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.DBERR,errmsg="参数不全")

    try:
        redis_sms_code = redis_store.get("sms_code:%s"%mobile)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="短信验证码取出失败")

    if not redis_sms_code:
        return jsonify(errno=RET.NODATA,errmsg="短信验证码已过期")

    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg="短信验证码填写错误")

    try:
        redis_store.delete("sms_code:%s"%mobile)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="短信验证码删除失败")

    user = User()

    user.nick_name = mobile
    # user.password_hash = password
    user.password = password
    user.mobile = mobile
    user.signature = "该用户很懒,什么都没写"

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="用户注册失败")

    return jsonify(errno=RET.OK,errmsg="注册成功")




# 短信发送成功
@passport_blue.route('/sms_code',methods=['POST'])
def sms_code():
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.DATAERR,errmsg="参数不全")

    try:
        redis_image_code = redis_store.get("image_code:%s"%image_code_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作redis失败")

    if not redis_image_code:
        return jsonify(errno=RET.NODATA,errmsg="图片验证码以过去")

    if image_code.upper() != redis_image_code.upper():
        return jsonify(errno=RET.DBERR,errmsg="图片验证码填写有误")

    try:
        redis_store.delete("image_code%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="删除redis图片验证码失败")

    sms_code = "%06d"%random.randint(0,999999)
    current_app.logger.debug("短信验证码是%s"%sms_code)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],1)
    #
    # if result == -1:
    #     return jsonify(errno=RET.DATAERR,errmsg="短信发送失败")
    #
    try:
        redis_store.set("sms_code:%s"%mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="图片保存到redis失败")

    return jsonify(errno=RET.OK,errmsg="短信发送成功")

@passport_blue.route('/image_code')
def image_code():

    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")

    name,text,image_data = captcha.generate_captcha()
    try:
        redis_store.set("image_code:%s"%cur_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)

        if pre_id:
            redis_store.delete("image_code:%s"%pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return "图片验证码操作失败"

    response = make_response(image_data)

    response.headers['Content-Type'] = 'image/png'

    return response